<template>
	<qh-page-view title="购买次卡">
		<block v-if="card_list.length">
			<block v-if="card.type==5">
				<view class="nocoupon">
					<view :class="'nav' + (activeIndex==0?' active':'')" @tap="changeIndex" data-index="0">商品列表</view>
					<view :class="'nav' + (activeIndex==1?' active':'')" @tap="changeIndex" data-index="1">次卡详情</view>
				</view>
			</block>
			<view v-if="activeIndex==0" class="goods-box">
				<block v-for="(item, index) in goodsList" :key="index">
					<view class="goods-list" :style="item.online_state!=1?'opacity: 0.6':''">
						<view class="goods_image" :data-index="index" @tap="toGoods">
							<image mode="widthFix" :src="item.goods_image"></image>
						</view>
						<view class="goods_bottom">
							<view class="goods-name" :data-index="index" @tap="toGoods">{{item.goods_name}}</view>
							<view class="goods_sku" v-if="item.attribute_state==2" @tap.stop="chooseSku" :data-index="index">
								<text>{{item.sku_name?item.sku_name:'选规格'}}</text>
								<image src="/static/images/arrow-right.png"></image>
							</view>
							<view class="goods_num">
								<view class="choose-sku-change border">
									<text class="qh-rt-single qh-rt-a-zu4424 choose-sku-change-icon" @click.stop="toChangeNum(1, index)"></text>
									<view class="choose-sku-num">
										<input v-if="!(item.goods_num<item.number)" data-index="index" min="1" type="number" @input="inputNum" @blur="blurGoods"
											:value="item.buy_num" :placeholder="item.number" placeholder-class="choose-sku-p"></input>
										<text v-else>{{skuInfo.buy_num}}</text>
									</view>
									<text class="qh-rt-single qh-rt-jia1 choose-sku-change-icon" @click.stop="toChangeNum(2, index)"></text>
								</view>
								<view>
									<view class="goods_price" v-if="showPlusPrice(item)">
										<text class="plus-price-color">￥{{item.plus_price}}</text>
										<text class="plus-price-icon">PLUS</text>
									</view>
									<view class="goods_price" v-if="showVipPrice(item)">
										<text class="price-color">￥{{item.shop_mem_price}}</text>
										<text class="vip-price-icon">VIP</text>
									</view>
									<view class="goods_price" v-if="showOnlinePrice(item)">￥{{item.online_price}}</view>
								</view>
							</view>
						</view>
						<view class="goods_disabled" v-if="item.online_state!=1">暂不可购买</view>
						<view class="goods_disabled" v-if="item.goods_num<item.number">库存不足</view>
					</view>
				</block>
			</view>
			<view v-if="activeIndex==1" class="list" v-for="(item, index) in card_list" :key="index">
				<view class="card_style">
					<view class="card_img">
						<image mode="widthFix" :src="item.image_url"></image>
					</view>
					<view class="card_text" :style="'color:'+item.card_name_color">
						<view class="card_name">{{item.name}}</view>
						<view class="card_time">购买截止日期：{{item.end_time}}</view>
					</view>
				</view>
				<view class="card_details">
					<view class="headline">
						<view></view>
						<view>次卡详情</view>
						<view></view>
					</view>
					<view class="details_list">
						<view class="details_left">次卡名称：</view>
						<view class="details_right">{{item.name}}</view>
					</view>
					<view class="details_list">
						<view class="details_left">使用规则：</view>
						<view class="details_right">{{item.use_rule}}</view>
					</view>
					<view class="details_list">
						<view class="details_left">可用时段：</view>
						<view class="details_right">{{item.time_interval}}</view>
					</view>
					<view class="details_list">
						<view class="details_left">有效日期：</view>
						<view class="details_right">{{item.effective_time}}</view>
					</view>
					<view class="details_list">
						<view class="details_left">购买截止日期：</view>
						<view class="details_right">{{item.end_time}}</view>
					</view>
					<view class="details_list">
						<view class="details_left">使用说明：</view>
						<view class="details_right">{{item.introduce}}</view>
					</view>
				</view>
			</view>
			<view class="bottom"></view>
			<view class="buy_now" v-if="card.status == 0" @tap.stop="buyNow">{{allMoney>0?(allMoney+' '):''}}立即购买</view>
			<view class="buy_no" v-if="card.status == 1">立即购买</view>
		</block>
		<!-- 规格 -->

		<block v-if="showSelectSku">
			<choose-sku :sku="sku" :goodsinfo="goods" :skuselect="skuSelect" :skutype="5" @close="closeSku"></choose-sku>
		</block>
	</qh-page-view>
</template>

<script>
	var app = getApp().globalData;
	export default {
		data() {
			return {
				card: {},
				activeIndex: 1,
				goodsList: [],
				showSelectSku: false,
				skuPrice: 0,
				skuNum: 0,
				selectSkuDetailId: -1,
				shopItemInfo: {},
				selectArr: [],
				skuDisabled: false,
				skuShopMmemStatus: 2,
				skuPlusMemStatus: 2,
				skuShopMemPrice: 0,
				skuPlusPrice: 0,
				selectGoodsSkuIndex: 0,
				shoppingIds: [],
				card_list: [],
				sku: {
					skuImg: '',
					//规格弹框图片
					skuName: '',
					//规格名称
					skuSelectIndex: [],
					//已选规格下标列表
					isSku: true,
					//是否是规格商品，针对扫码购
					shoppingNum: 1,
					//选择规格或扫码购商品详情时的加入购物车的数量
					canChangeCarNum: 1,
					//是否可以修改规格弹框数量
					user_type: 1,
					//用户类型  1普通  2plus  3常规会员
					skuPrice: '',
					//商品规格价
					skuNum: '',
					//商品规格库存
					skuShopMemStatus: 2,
					//规格商品是否开启普通会员价  1开启  2关闭
					skuShopMemPrice: '',
					//规格商品普通会员价
					skuPlusMemStatus: 2,
					//规格商品是否开启PLUS会员价  1开启  2关闭
					skuPlusPrice: '',
					//规格商品PLUS会员价
					sku_promotion_status: 0,
					//规格商品是否开启促销
					promotion_price: 0,
					//规格商品促销价
					canChangeAddNum: true,
					//是否可以增加
					goods_num: 0,
					showChangeNum: false,
					//是否显示选择数量
					btnText: '确定',
					//按钮文字
					disSkuClick: true //是否禁止点击确定选择按钮
				},
				skuDetailList: "",
				selectSkuName: "",
				pay_order_id: "",
				canClick: false,
				card_id: "",
				type: "",
				allMoney: "",
				user_type: "",
				goods: {},
				temSkuPrice: '',
				goods_index: 0,
			};
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		async onLoad(options) {
			await this.$onLaunched;
			// #ifdef MP-ALIPAY
			if (JSON.stringify(options) == '{}') {
				options = my.getLaunchOptionsSync().query;
			}
			// #endif
			var that = this;
			var id = options.card_id;
			if (options && options.store_id) {
				this.$store.store_id = options.store_id;
			}
			that.setData({
				card_id: id,
				type: options.type,
			});
			getApp().globalData.sendRequest({
				url: '/SubCard/cardInfo',
				type: "post",
				data: {
					type: options.type,
					card_id: id,
				},
				success: function(res) {
					if (res.status == 1) {
						if (options.type == 1) {
							if (res.sub_card.type == 5) {
								for (var i = 0; i < res.card_goods.length; i++) {
									if (res.card_goods[i].attribute_state == 2 && res.card_goods[i]
										.sku_id > 0) {
										res.card_goods[i].select_sku_id = res.card_goods[i].sku_id;
									}

									res.card_goods[i].buy_num = res.card_goods[i].number;
								}
							}

							that.setData({
								card: res.sub_card,
								activeIndex: res.sub_card.type == 4 ? 1 : 0,
								goodsList: res.card_goods ? res.card_goods : [],
								allMoney: res.sub_card.type == 4 ? res.sub_card.money : 0,
								user_type: res.user_type ? res.user_type : 1,
								card_list: [res.sub_card]
							});
						} else {
							if (res.card_bag.type == 5) {
								for (var i = 0; i < res.card_goods.length; i++) {
									if (res.card_goods[i].attribute_state == 2 && res.card_goods[i]
										.sku_id > 0) {
										res.card_goods[i].select_sku_id = res.card_goods[i].sku_id;
									}

									res.card_goods[i].buy_num = res.card_goods[i].number;
								}
							}

							that.setData({
								card: res.card_bag,
								activeIndex: res.card_bag.type == 4 ? 1 : 0,
								goodsList: res.card_goods ? res.card_goods : [],
								allMoney: res.card_bag.type == 4 ? res.card_bag.money : 0,
								user_type: res.user_type ? res.user_type : 1,
								card_list: res.card_list
							});
						}
					} else {
						that.setData({
							card: null
						});
						uni.showToast({
							title: res.msg,
							icon: 'none',
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					}
				}
			});
		},
		methods: {
			closeSku(data) {
				if (data) {
					console.log(this.goods_index)
					console.log(this.goodsList[this.goods_index])
					this.goodsList[this.goods_index].sku_name = data.selectSkuName;
					this.setData({
						selectSkuDetailId: data.selectSkuDetailId,
						selectArr: data.selectArr,
						selectSkuName: data.selectSkuName,
						temSkuPrice: data.temSkuPrice,
					})
					this.$forceUpdate()
					this.sureSku();
				} else {
					this.setData({
						showSelectSku: false
					})
				}
			},
			cratedSku: function() {
				var that = this;
				var skuDetailList = this.skuDetailList;
				var shopItemInfo = {};

				for (var i in skuDetailList) {
					shopItemInfo[skuDetailList[i].sku_id_list] = skuDetailList[i];
				}

				this.setData({
					shopItemInfo: shopItemInfo
				});
				this.checkItem();
			},
			checkSku: function(e) {
				if (this.sku.disSkuClick) {
					return;
				}

				var pIndex = e.currentTarget.dataset.pIndex;
				var cIndex = e.currentTarget.dataset.cIndex;
				var that = this;
				var sku = this.sku;
				var skuList = sku.skuList;
				var selectArr = this.selectArr;

				if (selectArr[pIndex] != skuList[pIndex].list[cIndex].id) {
					selectArr[pIndex] = skuList[pIndex].list[cIndex].id;
					sku.skuSelectIndex[pIndex] = cIndex;
				} else {
					selectArr[pIndex] = 0;
					sku.skuSelectIndex[pIndex] = -1;
				}

				this.setData({
					selectArr: selectArr,
					sku: sku
				});
				this.checkItem();
			},
			checkItem: function() {
				var that = this;
				var sku = this.sku;
				var option = sku.skuList;
				var selectArr = this.selectArr;
				var result = []; //定义数组存储被选中的值

				var goods = that.goodsList;

				for (var i in option) {
					result[i] = selectArr[i] ? selectArr[i] : 0;
				}

				for (var i in option) {
					var last = result[i];

					for (var k in option[i].list) {
						result[i] = option[i].list[k].id;
						option[i].list[k].status = this.isMay(result); //在数据里面添加字段isShow来判断是否可以选择
					}

					result[i] = last;
				}

				sku.skuList = option;
				var selectArr = this.selectArr;

				if (selectArr.indexOf(0) == -1) {
					var id_list = selectArr.join(','); //skuImg

					var goods_sku = this.shopItemInfo[id_list];
					var num = parseInt(goods_sku.goods_num);
					sku.skuImg = goods_sku.goods_img;
					sku.skuShopMemPrice = goods_sku.shop_mem_price;
					sku.skuPlusPrice = goods_sku.plus_price;
					sku.selectSkuName = goods_sku.name;
					sku.skuPrice = goods_sku.online_price;
					sku.skuNum = parseInt(goods_sku.goods_num);
					this.setData({
						selectSkuDetailId: goods_sku.id,
						sku: sku
					});
				} else {
					sku.skuImg = this.goods.goods_image;
					sku.skuShopMemPrice = this.goods.shop_mem_price;
					sku.skuPlusPrice = this.goods.plus_price;
					sku.selectSkuName = this.goods.goods_name;
					sku.skuPrice = this.goods.online_price;
					sku.skuNum = parseInt(this.goods.goods_num);
					this.setData({
						selectSkuDetailId: -1,
						sku: sku
					});
				}
			},
			isMay: function(result) {
				for (var i in result) {
					if (result[i] == 0) {
						return 1;
					}
				}

				var sku = this.shopItemInfo[result];

				if (sku && sku.goods_num * 1000 / 1000 >= 1) {
					return 1;
				} else {
					return 0;
				}
			},
			seeSkuBig: function() {
				var that = this;
				uni.previewImage({
					current: that.sku.skuImg,
					urls: [that.sku.skuImg] // 需要预览的图片http链接列表

				});
			},
			chooseSku: function(e) {
				var index = parseInt(e.currentTarget.dataset.index);
				this.showGoodsSku(index);
			},
			showGoodsSku: function(index) {
				var goodsList = this.goodsList;
				var skuSelectIndex = [];
				var selectArr = [];
				var skuDisabled = false;
				var sku = this.sku;

				if (goodsList[index].select_sku_id && goodsList[index].select_sku_id != '' && goodsList[index]
					.select_sku_id != 0) {
					skuDisabled = goodsList[index].sku_id > 0 ? true : false;
					var tempArr = goodsList[index].sku_id_list;
					tempArr = tempArr.split(',');

					for (var i = 0; i < tempArr.length; i++) {
						var arr = goodsList[index].skuAttr[i].list;

						for (var j = 0; j < arr.length; j++) {
							if (arr[j].id == tempArr[i]) {
								skuSelectIndex.push(j);
								selectArr.push(arr[j].id);
							}
						}
					}
				} else {
					for (var i = 0; i < goodsList[index].skuAttr.length; i++) {
						skuSelectIndex.push(-1);
						selectArr.push(0);
					}
				}

				sku.skuImg = goodsList[index].goods_image;
				sku.skuName = goodsList[index].goods_name;
				sku.skuSelectIndex = skuSelectIndex;
				sku.goods = goodsList[index];
				sku.skuShopMemPrice = goodsList[index].shop_mem_price;
				sku.skuPlusPrice = goodsList[index].plus_price;
				sku.skuShopMmemStatus = goodsList[index].shop_mem_status;
				sku.skuPlusMemStatus = goodsList[index].plus_mem_status;
				sku.skuList = JSON.parse(JSON.stringify(goodsList[index].skuAttr));
				sku.disSkuClick = goodsList[index].sku_id ? true : false;
				this.setData({
					selectSkuDetailId: 0,
					skuDetailList: goodsList[index].skuList,
					showSelectSku: true,
					selectGoodsSkuIndex: index,
					selectArr: selectArr,
					skuDisabled: skuDisabled,
					selectSkuName: '',
					sku: sku,
					goods: goodsList[index],
					goods_index: index,
				});
				// this.cratedSku();
			},
			//取消修改规格
			cancelSku: function() {
				// console.log(1)
				this.setData({
					showSelectSku: false
				});
			},
			//确认选择规格
			sureSku: function() {
				var selectSkuDetailId = this.selectSkuDetailId;

				if (selectSkuDetailId > 0) {
					var goods = this.goods;
					var goodsList = this.goodsList;
					var selectGoodsSkuIndex = this.selectGoodsSkuIndex;
					goodsList[selectGoodsSkuIndex].select_sku_id = selectSkuDetailId;
					goodsList[selectGoodsSkuIndex].sku_name = this.selectSkuName;
					goodsList[selectGoodsSkuIndex].sku_id_list = this.selectArr.join(',');
					this.setData({
						goodsList: goodsList,
						showSelectSku: false
					});
				} else {
					uni.showToast({
						title: '请完善规格',
						icon: 'none',
						duration: 1000
					});
				}
			},
			changeIndex: function(e) {
				this.setData({
					activeIndex: e.currentTarget.dataset.index
				});
			},
			//查看商品详情
			toGoods: function(e) {
				var index = parseInt(e.currentTarget.dataset.index);
				var goodsList = this.goodsList;

				if (goodsList[index].online_state == 1) {
					uni.navigateTo({
						url: '/pages/product/details/details?notBuy=1&id=' + goodsList[index].goods_id
					});
				}
			},
			//立即购买
			buyNow: function() {
				if (this.card.type == 4) {
					this.buyCard();
				} else {
					var goodsList = this.goodsList;

					for (var i = 0; i < goodsList.length; i++) {
						if (goodsList[i].goods_num < 1) {
							uni.showToast({
								title: '商品-' + goodsList[i].goods_name + '-库存不足',
								icon: 'none',
								mask: false
							});
							return;
						}

						if (goodsList[i].attribute_state == 2) {
							if ((goodsList[i].sku_id == '' || goodsList[i].sku_id == 0) && !goodsList[i]
								.select_sku_id) {
								this.showGoodsSku(i);
								return;
							}
						}
					}

					uni.showLoading({
						title: '请求中...'
					});
					this.setData({
						shoppingIds: []
					});
					this.addShopping(0);
				}
			},
			addShopping: function(i) {
				var goodsList = this.goodsList;
				var shoppingIds = this.shoppingIds;
				var that = this;
				getApp().globalData.sendRequest({
					url: '/Shopping/addShopping_v1',
					type: "post",
					showLoading: false,
					data: {
						goods_id: goodsList[i].goods_id,
						num: goodsList[i].buy_num ? goodsList[i].buy_num : 1,
						type: 2,
						sku_id: goodsList[i].select_sku_id ? goodsList[i].select_sku_id : ''
					},
					success: function(res) {
						if (res.status == 1) {
							shoppingIds.push(res.id);
							that.setData({
								shoppingIds: shoppingIds
							});

							if (goodsList.length > i + 1) {
								that.addShopping(i + 1);
							} else {
								uni.hideLoading();
								uni.navigateTo({
									url: '../../order/Settlement/Settlement?shopping_ids=' + JSON
										.stringify(shoppingIds) + '&card_type=' + that.type +
										'&card_id=' + that.card.id
								});
							}
						} else {
							uni.hideLoading();
							uni.showToast({
								title: res.msg ? res.msg : '请求发生错误，请稍后重试',
								icon: 'none',
								duration: 1500,
								mask: false
							});
						}
					},
					fail: function(res) {
						uni.hideLoading();
						uni.showToast({
							title: res.msg ? res.msg : '请求发生错误，请稍后重试',
							icon: 'none',
							duration: 1500,
							mask: false
						});
					}
				});
			},
			//直接购买次卡
			buyCard: function() {
				var that = this;
				getApp().globalData.sendRequest({
					url: '/SubCard/placeOrder',
					type: "post",
					loadTitle: '下单中',
					data: {
						type: that.type,
						//1次卡 2卡包
						card_id: that.card_id,
						pay_type: 1, //微信支付,

					},
					success: function(res) {
						if (res.status == 1) {
							that.setData({
								pay_order_id: res.pay_order_id
							});
							that.uni_pay(res.pay_data.data);
						} else {
							uni.showModal({
								title: '提示',
								content: res.msg
							});
							that.setData({
								pay_order_id: null
							});
						}
					}
				});
			},
			//修改购买数量
			toChangeNum(_type, index) {
				let goodsList = this.goodsList;
				let item = this.goodsList[index];
				if (_type == 1 && !((item.number * 1 + 1) <= item.buy_num && item.buy_num > 1 && item.goods_num > item.number)) return;
				if (_type == 2 && !((item.buy_num + 1) <= item.goods_num && item.goods_num * 1 > item.number * 1)) return;
				
				if (_type == 1 && goodsList[index].buy_num <= goodsList[index].number) {
					goodsList[index].buy_num = goodsList[index].number;
				}

				if (_type == 2 && goodsList[index].buy_num >= goodsList[index].goods_num) {
					goodsList[index].buy_num = goodsList[index].goods_num;
				}

				var buy_num = _type == 1 ? goodsList[index].buy_num * 1 - 1 : goodsList[index].buy_num * 1 + 1;
				goodsList[index].buy_num = buy_num;
				this.setData({
					goodsList: goodsList
				});
			},
			//输入购买数量
			inputNum: function(e) {
				var index = parseInt(e.currentTarget.dataset.index);
				var goodsList = this.goodsList;
				var number = e.detail.value;
				goodsList[index].buy_num = number;
				this.setData({
					goodsList: goodsList
				});
			},
			//输入购买数量失焦
			blurGoods: function(e) {
				var that = this;
				var index = parseInt(e.currentTarget.dataset.index);
				var goodsList = this.goodsList;
				var buy_num = goodsList[index].buy_num;

				if (buy_num < goodsList[index].number) {
					buy_num = goodsList[index].number;
				}

				goodsList[index].buy_num = buy_num;
				that.setData({
					goodsList: goodsList
				});
			},
			// 调取支付。。。
			uni_pay: function(payData) {
				console.log(payData, 'payData')
				var that = this;
				// 微信支付
				// #ifdef MP-WEIXIN
				uni.requestPayment({
					timeStamp: payData.timeStamp,
					nonceStr: payData.nonceStr,
					package: payData.package,
					signType: payData.signType,
					paySign: payData.paySign,
					success: function(re) {
						if (re.errMsg == 'requestPayment:ok') {
							// 查询订单支付状态
							uni.showLoading({
								title: '订单信息查询中',
								mask: true,
							});
							var count = 0;
							var flag = true;
							that.payOut(0); //查询订单
						} else {
							console.log(re);
							that.setData({
								canClick: true
							});
						}
					},
					complete: function(res) {
						console.log(res);
						that.setData({
							canClick: true
						});
					}
				});

				// #endif

				// 支付宝支付

				// #ifdef MP-ALIPAY
				my.tradePay({
					tradeNO: payData.trade_no,
					success: function(re) {
						if (re.errMsg == 'requestPayment:ok') {
							// 查询订单支付状态
							uni.showLoading({
								title: '订单信息查询中',
							});
							var count = 0;
							var flag = true;
							that.payOut(0); //查询订单
						} else {
							console.log(re);
							that.setData({
								canClick: true
							});
						}
					},
					complete: function(res) {
						console.log(res);
						that.setData({
							canClick: true
						});
					}
				});

				// #endif

			},
			//付款完成
			payOut: function() {
				var that = this;
				var userInfo = uni.getStorageSync('userInfo');
				getApp().globalData.sendRequest({
					url: '/SubCard/checkPay',
					type: "post",
					data: {
						pay_order_id: that.pay_order_id,
						//订单id
						vip_id: userInfo.vid //会员id

					},
					success: function(res) {
						if (res.status == 1) {
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										uni.navigateBack({
											delta: 1
										});
									}
								}
							});
						} else if (res.status == 2) {
							count++;

							if (count > 10) {
								uni.hideLoading();
								uni.showModal({
									title: '提示',
									content: res.msg,
									showCancel: false,
									confirmText: '确定',
									confirmColor: '#fd633a'
								});
							} else {
								setTimeout(function() {
									that.payOut(count);
								}, 1000);
							}
						} else {
							uni.showModal({
								title: '提示',
								content: res.msg
							});
						}
					}
				});
			},
			// 展示plus会员价条件
			showPlusPrice(item) {
				return app.showPlusPrice(item)
			},
			
			// 展示会员价条件
			showVipPrice(item) {
				return app.showVipPrice(item)
			},
			
			// 展示普通价格
			showOnlinePrice(item) {
				return app.showOnlinePrice(item)
			}
		}
	};
</script>
<style>
	@import "./buySubCard.css";

	.plus_price_icon {
		width: 70rpx;
		height: 30rpx;
	}
</style>
